<template>
  <!--<PageWrapper dense contentFullHeight fixedHeight contentClass="flex">-->
  <!--<BasicTable @register="registerTable" class="w-2/3 xl:w-3/4">-->
  <!--<template #action="{ record }">-->
  <!--<TableAction-->
  <!--:actions="[-->
  <!--{-->
  <!--icon: 'clarity:note-edit-line',-->
  <!--auth: 'menu:edit',-->
  <!--onClick: handleEdit.bind(null, record),-->
  <!--},-->
  <!--{-->
  <!--icon: 'ant-design:delete-outlined',-->
  <!--auth: 'menu:delete',-->
  <!--color: 'error',-->
  <!--popConfirm: {-->
  <!--title: t('是否确认删除'),-->
  <!--confirm: handleDelete.bind(null, record),-->
  <!--},-->
  <!--},-->
  <!--]"-->
  <!--/>-->
  <!--</template>-->
  <!--</BasicTable>-->
  <!--<AccountModal @register="registerModal" @success="handleSuccess" />-->
  <!--</PageWrapper>-->
  <div class="system-user">
    <div>
      <a-form :model="searchQuery" class="search-item">
        <a-form-item label="角色名称" class="search-item-box">
          <a-input v-model:value="pageForm.roleName" style="width: 220px;" placeholder="请输入角色名称"/>
        </a-form-item>
        <a-button type="primary" danger class="search-btn" @click="searchbtn">查询</a-button>
        <a-button type="primary" danger style="position: absolute;right: 36px;" @click="addRole('新增','')">新增角色</a-button>
      </a-form>
    </div>
    <div style="padding:16px;" class="sticky">
      <a-table :dataSource="dataSource" :columns="columns" :pagination="false" :scroll="{ y: 650 }">
        <template #index="{ index }">
          {{ index + 1 }}
        </template>
        <template #operation="{ record }">
          <a-button v-if="record.remark === 'admin'" style="border: 0;background: none;" disabled>设置权限</a-button>
          <a-button v-else class="btn" style="color:#0081ff;" @click="addRole('修改',record)">设置权限</a-button>
          <a-button v-if="record.remark != 'user' && record.remark != 'admin'" class="btn" @click="handleDelete(record)">删除</a-button>
          <a-button v-else style="border: 0;background: none;" disabled>删除</a-button>
        </template>
      </a-table>
      <div class="otherPagination">
        <div class="seizeASeat"> </div>
        <a-pagination
          size="small"
          :total="pageForm.total"
          :pageSize="pageForm.size"
          :current="pageForm.limit"
          :hideOnSinglePage="true"
          :showSizeChanger="false"
          @change="changePage"
          class="pag"
        />
      </div>
    </div>

    <!-- 设置角色 -->
    <a-modal
      v-model:visible="isAdd"
      :maskClosable="false"
      :width="550"
      :centered="true"
      okText="确认"
      :title="modalTitle"
      @ok="savaAdd"
      @cancel="close"
      style="padding: 20px"
    >
      <a-form
        :model="addModelForm"
        :label-col="{ span: 6 }"
        :wrapper-col="12"
        style="margin-top: 16px"
        ref="formRef"
        :rules="rules"
      >
        <a-form-item label="角色名称" name="roleName">
          <a-input
            v-model:value="addModelForm.roleName"
            placeholder="请输入角色名称"
            style="width: 320px"
            type="text"
          />
        </a-form-item>
        <a-form-item label="权限字符">
          <a-input
            v-model:value="addModelForm.menuCode"
            placeholder="权限字符自动生成"
            disabled
            style="width: 320px"
            type="text"
          />
        </a-form-item>
        <a-form-item label="角色顺序" name="roleNumber">
          <a-input
            v-model:value="addModelForm.roleNumber"
            controls-position="right" :min="0"
            style="width: 320px"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="addModelForm.status">
            <a-radio :value="1" style="text-align: center">正常</a-radio>
            <a-radio :value="0" style="text-align: center">停用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="菜单权限">
          <a-checkbox style="height: 32px;line-height: 32px;" v-model="menuExpand" @change="handleCheckedTreeExpand()">展开/折叠</a-checkbox>
          <a-checkbox style="height: 32px;line-height: 32px;" v-model="menuNodeAll" @change="handleCheckedTreeNodeAll()">全选/全不选</a-checkbox>
          <!--<a-checkbox v-model="addModelForm.menuCheckStrictly" @change="handleCheckedTreeConnect()">父子联动</a-checkbox>-->
          <a-tree ref="treeRef" v-if="menuOptions.length > 0" style="margin-top: 8px;" class="tree-border" :checkedKeys="computedCheckedKeys"
                  @check="onCheck" checkable :tree-data="menuOptions" :default-expand-all="isExpanded" :replaceFields="{ key:'id',title:'title',children:'children'}"
                   empty-text="加载中，请稍候"></a-tree>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 删除角色 -->
    <a-modal v-model:visible="dialogDelete" :maskClosable="false" :width="380" :centered="true" :destroyOnClose="true" title="删除"
             class="remove-model-dialog" @cancel="dialogClose">
      <div class="remove-indicator-tip">是否确定删除</div>
      <template #footer>
        <div class="dialog-footer-box">
          <div class="cancel-btn" @click="dialogClose">取消</div>
          <div class="ok-btn" @click="handleOk">确定</div>
        </div>
      </template>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref,nextTick,onMounted,h,createVNode } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { getRolePageList,addSave,Modify,Delete } from '/@/api/system/role';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getMenus } from '/@/utils/menu'
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Tree,Modal,Switch } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { getMenuPermission } from '/@/api/checkToken';
  const { t } = useI18n();

  let pageForm = ref({
    size: 10,
    limit: 1,
    total: 0,
    roleName:''
  });
  function changePage(val) {
    pageForm.value.limit = val;
    // todo
    getList();
  }
  let dataSource = ref([]);
  let columns = ref([
    {
      title: '序号',
      align: 'left',
      width: 100,
      dataIndex: 'index',
      key: 'index',
    },
    {
      title: t('角色名称'),
      dataIndex: 'roleName',
      align: 'left',
    },
    {
      title: t('角色编码'),
      dataIndex: 'menuCode',
      align: 'left',
    },
    {
      title: t('状态'),
      dataIndex: 'status',
      align: 'left',
      customRender: ({ record }) => {
        if (!Reflect.has(record, 'pendingStatus')) {
          record.pendingStatus = false;
        }
        return h(Switch, {
          checked: record.status === 1,
          // checkedChildren: t('已启用'),
          // unCheckedChildren: t('已禁用'),
          loading: record.pendingStatus,
          onChange(checked: boolean) {
            record.pendingStatus = true;
            const newStatus = checked ? 1 : 0;
            const {createMessage} = useMessage();
            let queryData = {
              status: newStatus,
            };
            queryData.roleIds=[record.id]
            Modify(queryData).then(() => {
                // createMessage.success(t('已成功修改角色状态'));
              })
              .catch(() => {
                // createMessage.error(t('修改角色状态失败'));
              })
              .finally(() => {
                record.pendingStatus = false;
              });
            getList()
          },
        });
      }
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      align: 'left',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      slots: { customRender: 'operation' },
      align: 'left',
    },
  ]);

  getList()

  async function getList() {
    let queryData = {
      limit: pageForm.value.limit,
      size: pageForm.value.size,
    };
    if(pageForm.value.roleName){
      queryData.roleName=pageForm.value.roleName
    }
    let res = await getRolePageList(queryData);
    let needCurrentPage = res.currentPage;
    dataSource.value = res.list.map((item, index) => {
      return {
        ...item,
        index: needCurrentPage * 10 - 10 + index + 1,
      };
    });

    pageForm.value.total = res.total;
  }

  function searchbtn() {
    pageForm.value['pageNum'] = 1;
    pageForm.value['pageSize'] = 20;
    getList()
  }

  //新增
  async function getMenuList () {
    return getMenus()
  };
  const menuOptions = ref(getMenus());

  let modalTitle = ref('');
  let roleId = ref('');
  let details = ref({});
  let addModelForm = ref({
    id: '', //id
    roleName: null,
    menuPermission: '',
    menuCode: '',
    status: 1,
    roleNumber: '',
  });
  const isAdd = ref(false);

  const computedCheckedKeys = ref(['1419273699992498188']);
  const addRole = (value,item) => {
    modalTitle.value = value;
    if(item){
      roleId.value=item.id;
      addModelForm.value.roleName=item.roleName;
      addModelForm.value.status=item.status;
      addModelForm.value.roleNumber=item.roleNumber;
      addModelForm.value.menuCode=item.menuCode;

      let menuPermission=JSON.parse(item.menuPermission)
      let arrID=[];
      for(let i=0; i<menuPermission.length; i++){
        arrID.push(menuPermission[i].id)
        if(menuPermission.length > 0){
          for(let j=0; j<menuPermission[i].children.length; j++){
            arrID.push(menuPermission[i].children[j].id)
          }
        }
      }
      computedCheckedKeys.value=arrID
    }
    isAdd.value = true;
  };
  const dialogDelete = ref(false);
  function dialogClose() {
    dialogDelete.value=false;
  }
  function handleDelete(record) {
    dialogDelete.value=true;
    roleId.value=record.id;
  }
  const { notification } = useMessage();
  async function handleOk (){
    const queryData={
      roleIds:[roleId.value]
    }
    await Delete(queryData);
    dialogDelete.value=false;
    // notification.success({
    //   message: t('提示'),
    //   description: t('删除成功'),
    // });
    getList()
  };
  let rules = ref({
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    roleNumber: [{ required: true, message: '请输入角色顺序', trigger: 'blur' }],
  });

  // const treeRef = ref<Nullable<HTMLElement>>(null);
  const treeRef = ref(null);
  const menuExpand = ref(false);
  const menuNodeAll = ref(false);
  const isExpanded = ref(false);

  // const handleCheckedTreeExpand = (type: any) => {
  //   nextTick(() => {
  //     console.log(treeRef.value,"treeRef.valuetreeRef.value")
  //     if (type) {
  //       menuExpand.value = true;
  //       Object.values(treeRef.value.store.nodesMap).forEach((v: any) => v.expand());
  //       return;
  //     }
  //     menuExpand.value = false;
  //     Object.values(treeRef.value.store.nodesMap).forEach((v: any) => v.collapse());
  //   })
  // };

  // 树权限（展开/折叠）
  function handleCheckedTreeExpand() {
    menuOptions.value=[]
    isExpanded.value = !isExpanded.value;
    nextTick(() => {
      menuOptions.value=getMenus()
    })
  }
  let checkedNodes=[]
  let computedCheckedList=ref([])

  const onCheck = (checkedKeys, info) => {
    let checkedNodelIist=[]
    computedCheckedKeys.value=checkedKeys;
    let arr = JSON.parse(JSON.stringify(menuOptions.value));
    let parent= searchParentNode(arr, info.node.parentId);

    if(parent){
      checkedNodelIist.push(JSON.parse(JSON.stringify(parent)))
    }
    checkedNodelIist=arrDistinctByProp(checkedNodelIist,'id');
    let childrenArr=[]
    if (info.checked) {
      if(info.node.type === 1){
        for (let i = 0; i < info.checkedNodes.length; i++) {
          if(!info.checkedNodes[i].parentId){
            // info.checkedNodes[i].isTrouble=!info.checkedNodes[i].isTrouble
            checkedNodelIist.push(info.checkedNodes[i])
          }
        }
        if(checkedList.value.length > 0){
          checkedList.value=checkedNodelIist
          // for (let i = 0; i < checkedList.value.length; i++) {
          //   for (let j = 0; j < checkedNodelIist.length; j++) {
          //     if(checkedList.value[i].id === checkedNodelIist[j].id){
          //       checkedList.value[i]=checkedNodelIist[j]
          //     }
          //   }
          // }
        }
      }else if(info.node.type === 2){
        for (let i = 0; i < checkedNodelIist.length; i++) {
          // if(checkedNodelIist[i].id === info.node.parentId){
          let arrList=[]
          for (let j = 0; j < checkedNodelIist[i].children.length; j++) {
            for (let q = 0; q < info.checkedNodes.length; q++) {
              if(checkedNodelIist[i].children[j].id === info.checkedNodes[q].id){
                arrList=arrList.concat(info.checkedNodes[q])
              }
            }
          }
          checkedNodelIist[i].children=arrList;
        }
        if(checkedList.value.length > 0){
          for (let i = 0; i < checkedList.value.length; i++) {
            for (let j = 0; j < checkedNodelIist.length; j++) {
              if(checkedList.value[i].id === checkedNodelIist[j].id){
                checkedList.value[i]=checkedNodelIist[j]
              }
            }
          }
        }
      }
    }else {

      if(checkedList.value.length > 0){
        for (let i = 0; i < checkedList.value.length; i++) {
          let arrList=[]
          if(info.node.type === 1 && checkedList.value[i].id === info.node.id){
            // checkedList.value.splice(i,1)
          }else {
            for (let j = 0; j < checkedList.value[i].children.length; j++) {
              for (let q = 0; q < info.checkedNodes.length; q++) {
                if(checkedList.value[i].children[j].id === info.checkedNodes[q].id){
                  arrList=arrList.concat(info.checkedNodes[q])
                }
              }
            }
          }
          checkedList.value[i].children=arrList;
        }
      }else {
        for (let i = 0; i < checkedNodelIist.length; i++) {
          let arrList=[]
          for (let j = 0; j < checkedNodelIist[i].children.length; j++) {
            for (let q = 0; q < info.checkedNodes.length; q++) {
              if(checkedNodelIist[i].children[j].id === info.checkedNodes[q].id){
                arrList=arrList.concat(info.checkedNodes[q])
              }
            }
          }
          checkedNodelIist[i].children=arrList;
        }
      }
    }
    if(checkedNodes.length > 0){
      for (let i = 0; i < checkedNodes.length; i++) {
        for (let j = 0; j < checkedNodelIist.length; j++) {
          if(checkedNodes[i].id === checkedNodelIist[j].id){
            checkedNodes[i]=checkedNodelIist[j]
          }
        }
      }
    }
    // console.log(checkedNodelIist,"checkedNodelIist")

    // console.log(checkedNodes,"checkedNodes")
    checkedNodes=checkedNodes.concat(checkedNodelIist)
    const res = new Map();
    checkedNodes= checkedNodes.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));

    if(checkedList.value.length > 0){
      computedCheckedList.value=checkedList.value
    }else {
      computedCheckedList.value=checkedNodes;
    }
    // console.log(computedCheckedList.value,"computedCheckedListcomputedCheckedList")
  };

  function arrDistinctByProp(arr,prop){
    //只返回第一次出现的，重复出现的过滤掉
    return arr.filter(function(item,index,self){
      return self.findIndex(el=>el[prop]==item[prop])===index
    })

  }

  //找到所有父层级
  function searchParentNode(nodes, parentId) {
    for (const node of nodes) {
      if (node.id === parentId) {
        return node; // 返回找到的父节点
      }
      if (node.children) {
        const parentNode = searchParentNode(node.children, parentId);
        if (parentNode) return parentNode; // 如果在子节点中找到，返回父节点
      }
    }
    return null; // 如果没有找到，返回null
  }

  let checkedList=ref([])
  // 树权限（全选/全不选）
  const handleCheckedTreeNodeAll = async (type) => {
    menuNodeAll.value=!menuNodeAll.value;
    let checkedKeys=[]
    let arr = JSON.parse(JSON.stringify(menuOptions.value));
    if(menuNodeAll.value){
      for (let i = 0; i < arr.length; i++) {
        checkedKeys.push(arr[i].id)
        if(arr[i].children){
          for (let j = 0; j < arr[i].children.length; j++) {
            checkedKeys.push(arr[i].children[j].id)
          }
        }
      }
      computedCheckedList.value=arr
      checkedList.value=arr
    }else {
      checkedKeys=[]
      computedCheckedList.value=[]
      checkedList.value=[]
    }
    computedCheckedKeys.value=checkedKeys;

  }
  const getAllNodeKeys = (nodes: Tree[], keys: number[] = []) => {
    nodes.forEach((node) => {
      keys.push(node.id);
      if (node.children) {
        getAllNodeKeys(node.children, keys);
      }
    });
    return keys;
  };
  async function savaAdd (){
    let queryData = {
      roleName: addModelForm.value.roleName,
      status: addModelForm.value.status,
      roleNumber: addModelForm.value.roleNumber,
      menuPermission: addModelForm.value.menuPermission,
    };
    if(addModelForm.value.menuCode){
      queryData.menuCode=addModelForm.value.menuCode
    }
    if(computedCheckedKeys.value.length > 0){
      // queryData.menuPermission=computedCheckedKeys.value.join()
      queryData.menuPermission=JSON.stringify(computedCheckedList.value)
    }
    // console.log(JSON.stringify(computedCheckedList.value))
    // console.log(JSON.parse(JSON.stringify(computedCheckedList.value)))
    //
    let arr=JSON.parse(JSON.stringify(computedCheckedList.value))
    for (let i = 0; i < arr.length; i++) {
      if(arr[i].children.length === 0){
        arr.splice(i,1)
      }
    }
    if(modalTitle.value === '新增'){
      let res = await addSave(queryData);
    }
    if(modalTitle.value === '修改'){
      if(roleId.value){
        queryData.roleIds=[roleId.value]
      }
      let res = await Modify(queryData);
    }

    isAdd.value = false;
    getList();

    getMenuPermission(localStorage.getItem('userId')).then((res) => {
      localStorage.setItem('menuPermissionList', res.menuPermission);
      window.location.reload()
    }).catch(() => {});

  }
  function close() {
    addModelForm = ref({
      id: '', //id
      roleName: null,
      menuPermission: '',
      menuCode: '',
      status: 1,
      roleNumber: '',
    });
    computedCheckedKeys.value=[]
  }
</script>
<style lang="less">
  .system-user{
    background: #ffffff;
    .search-item{
      display:flex;
      padding: 16px 16px 0 16px;
    }
    .search-item-box{
      display:flex;
      margin-right: 16px;
      /*width: 300px;*/
    }
    .btn{
      border: 0;
      color: #C11A20;
      box-shadow:none;
      background: none;
    }
  }
  .remove-model-dialog {
    .ant-modal-header {
      height: 56px;
      padding: 0px 20px;
      display: flex;
      align-items: center;
    }

    .ant-modal-body {
      padding: 32px 20px !important;
      box-sizing: border-box;

      .remove-indicator-tip {
        color: #303133;
        font-size: 14px;
        font-weight: 500;
        line-height: 22px;
      }
    }

    .ant-modal-footer {
      height: 62px;
      padding: 10px 20px 20px 20px;
      border-top: unset;
      box-sizing: border-box;

      .dialog-footer-box {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .ok-btn,
        .cancel-btn {
          font-size: 14px;
          padding: 0px 16px;
          border-radius: 4px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
        }

        .cancel-btn {
          border: 1px solid #DCDFE6;
          color: #606266;

          &:hover {
            border-color: #C11A20;
            color: #C11A20;
          }
        }

        .ok-btn {
          background: #C11A20;
          color: #fff;
          margin-left: 12px;
        }
      }
    }

    .ant-modal-close {
      top: 20px;
      right: 20px;

      .ant-modal-close-x {
        width: 16px;
        height: 16px;
        line-height: 1;
      }
    }
  }
</style>
